Page({
  data: {
    keyword: '',
    results: [],
    hotSearches: ['周杰伦', '邓紫棋', '薛之谦', '毛不易', '陈奕迅', '林俊杰'],
    searchHistory: [],
    showResults: false
  },

  onLoad() {
    this.loadSearchHistory()
    // 加载所有歌单的歌曲数据
    const config = require('../../utils/config')
    this.allSongs = []
    
    // 收集首页6种歌单的所有歌曲
    for (let i = 1; i <= 6; i++) {
      const songs = config.getPlaylistSongs(i)
      this.allSongs = this.allSongs.concat(songs)
    }
  },

  onShow() {
    this.loadSearchHistory()
    // 更新收藏状态
    this.updateFavoriteStatus()
  },



  // 加载搜索历史
  loadSearchHistory() {
    const history = wx.getStorageSync('searchHistory') || []
    this.setData({
      searchHistory: history.slice(0, 10)
    })
  },

  // 保存搜索历史
  saveSearchHistory(keyword) {
    if (!keyword.trim()) return
    
    let history = wx.getStorageSync('searchHistory') || []
    history = history.filter(item => item !== keyword)
    history.unshift(keyword)
    
    if (history.length > 20) {
      history = history.slice(0, 20)
    }
    
    wx.setStorageSync('searchHistory', history)
    this.setData({
      searchHistory: history.slice(0, 10)
    })
  },

  // 输入框变化
  onInput(e) {
    const keyword = e.detail.value
    this.setData({
      keyword: keyword
    })
    
    // 实时搜索（当输入超过1个字符时）
    if (keyword.trim().length > 0) {
      this.performSearch(keyword.trim())
    } else {
      // 清空搜索结果
      this.setData({
        results: [],
        showResults: false
      })
    }
  },

  // 执行搜索
  performSearch(keyword) {
    if (!keyword.trim()) {
      this.setData({
        results: [],
        showResults: false
      })
      return
    }

    // 从所有歌曲中搜索匹配项（匹配歌曲名或歌手名）
    const keywordLower = keyword.toLowerCase().trim()
    const matchedSongs = this.allSongs.filter(song => 
      song.name.toLowerCase().includes(keywordLower) || 
      song.artist.toLowerCase().includes(keywordLower)
    )

    // 添加收藏状态
    const app = getApp()
    const songsWithFavoriteStatus = matchedSongs.map(song => ({
      ...song,
      isFavorite: app.isFavorite(song.id)
    }))

    this.setData({
      results: songsWithFavoriteStatus,
      showResults: true
    })
  },

  // 搜索功能 - 从所有歌单中查找匹配的歌曲
  search(keyword) {
    const searchKeyword = keyword || this.data.keyword
    if (!searchKeyword.trim()) {
      wx.showToast({
        title: '请输入搜索关键词',
        icon: 'none'
      })
      return
    }

    // 保存搜索历史
    this.saveSearchHistory(searchKeyword.trim())

    // 执行搜索
    this.performSearch(searchKeyword.trim())

    if (this.data.results.length > 0) {
      wx.showToast({
        title: `找到 ${this.data.results.length} 首歌曲`,
        icon: 'success'
      })
    }
  },

  // 点击搜索按钮
  onSearch() {
    this.search()
  },

  // 点击热门搜索
  onHotSearchTap(e) {  // 修复方法名拼写错误
    const keyword = e.currentTarget.dataset.keyword
    this.setData({
      keyword: keyword
    })
    this.search(keyword)
  },

  // 点击历史搜索
  onHistoryTap(e) {  // 修复方法名拼写错误
    const keyword = e.currentTarget.dataset.keyword
    this.setData({
      keyword: keyword
    })
    this.search(keyword)
  },

  // 清空搜索历史
  clearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定要清空搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('searchHistory')
          this.setData({
            searchHistory: []
          })
          wx.showToast({
            title: '已清空',
            icon: 'success'
          })
        }
      }
    })
  },

  // 播放歌曲
  playSong(e) {
    const song = e.currentTarget.dataset.song
    
    if (!song) return

    const app = getApp()
    
    // 创建完整的歌曲对象
    const fullSong = {
      id: song.id,
      name: song.name,
      artist: song.artist,
      picUrl: song.picUrl,
      url: `https://music.example.com/song/${song.id}.mp3`,
      duration: song.duration
    }

    // 设置当前播放列表
    app.globalData.currentPlaylist = this.data.results
    app.globalData.currentSongIndex = this.data.results.findIndex(item => item.id === song.id)
    
    // 播放歌曲
    app.playSong(fullSong)
    
    wx.showToast({
      title: `正在播放: ${song.name}`,
      icon: 'success'
    })

    // 跳转到播放页面
    setTimeout(() => {
      wx.navigateTo({
        url: `/pages/player/player?musicId=${song.id}&name=${encodeURIComponent(song.name)}&artist=${encodeURIComponent(song.artist)}&cover=${encodeURIComponent(song.picUrl || '/assets/default-cover.svg')}&duration=${encodeURIComponent(song.duration || '00:00')}`
      })
    }, 1000)
  },

  // 切换收藏状态
  toggleFavorite(e) {
    e.stopPropagation()
    const song = e.currentTarget.dataset.song
    const app = getApp()
    
    // 使用app中的统一收藏方法
    const result = app.toggleFavorite(song)
    
    // 更新收藏状态
    this.updateFavoriteStatus()
  },

  // 更新收藏状态
  updateFavoriteStatus() {
    const app = getApp()
    const results = this.data.results.map(song => ({
      ...song,
      isFavorite: app.isFavorite(song.id)
    }))
    
    this.setData({
      results: results
    })
  },

  // 返回首页
  goHome() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  }
})